﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.Services;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/")]
    public class ChartController : ControllerBase
    {
        private readonly IChartService _chartService;
        private readonly ICharSaveService _charSaveService;
        private readonly IChartDataService _chartDataService;
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<ChartController> _logger;

        public ChartController(IChartService chartService, ICharSaveService charSaveService, IChartDataService chartDataService ,IWebHostEnvironment env, ILogger<ChartController> logger)
        {
            _chartService = chartService;
            _charSaveService = charSaveService;
            _chartDataService = chartDataService;
            _env = env;
            _logger = logger;
        }

        [HttpGet("dashboard/config")]
        public async Task<IActionResult> GetConfigJson()
        {
            try
            {
                // 调用服务层获取JSON字符串
                string jsonData = await _chartService.GetDashboardConfigAsync();

                // 返回JSON（框架自动序列化）
                return Ok(jsonData);
            }
            catch (Exception ex)
            {
                return StatusCode(500, "服务器错误: " + ex.Message); // 错误处理 [[7]]
            }
        }
        [HttpGet("dashboard/line")]
        public async Task<IActionResult> GetLineData([FromQuery] string cCusName,
        [FromQuery] string cCusTableName,
        [FromQuery] string xAxis,
        [FromQuery] string yAxis)
        {
            try
            {
                LineDataDTO linedata = await _chartService.GetLineData(cCusName,cCusTableName,xAxis,yAxis);

                // 返回JSON（框架自动序列化）
                return Ok(linedata);
            }
            catch (Exception ex)
            {
                return StatusCode(500, "服务器错误: " + ex.Message); // 错误处理 [[7]]
            }
        }
        [HttpPost("save/select/{BIMainTableName}")]
        public async Task<ActionResult<int>> SaveBeforeSelectByNameConfig(string BIMainTableName)
        {
            try
            {
                int count = await _charSaveService.SaveBeforeSelectByName(BIMainTableName);
                return count;
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"查询数据库时发生错误: {ex.Message}");
            }
        }

        [HttpPost("save/charts")]
        public async Task<IActionResult> SaveConfig([FromBody] DashboardRequestWrapper request)
        {
            var config = request.DashboardConfig;
            _logger.LogInformation("收到请求，数据: {@Config}", config);

            try
            {
                var containerId = config.Items?.FirstOrDefault()?.Id;
       

                // 1. 保存主表
                var mainTableId = await _charSaveService.SaveBIMainTableAsync( 
                    config.Name,
                    config.CreatedAt,
                    config.BIMainTableId,
                    config.BackgroundColor,
                    config.iCusID ?? 0);

                // 2. 保存所有顶级容器（关键：为顶级容器按顺序设置Sort）
                if (config.Items.Any())
                {
                    // 遍历顶级容器时，按索引+1设置Sort（1,2,3...）
                    for (int i = 0; i < config.Items.Count; i++)
                    {
                        var container = config.Items[i];
                        // 为顶级容器赋值Sort（从1开始，与顺序对应）
                        container.Sort = i + 1;
                        // 保存顶级容器（无父容器）
                        await _charSaveService.SaveContainerAsync(container, mainTableId);
                    }
                }

                return Ok(new
                {
                    success = true,
                    message = "配置保存成功",
                    data = new { mainTableId }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存配置失败");
                return StatusCode(500, new
                {
                    success = false,
                    message = "保存失败",
                    detail = ex.Message
                });
            }
        }
        [HttpGet("main/{bimMainTableId}")]
        public async Task<ActionResult<DashboardConfigDto>> GetDashboardConfig(string bimMainTableId)
        {
            try
            {
                var config = await _chartDataService.GetDashboardConfigAsync(bimMainTableId);
                if (config == null)
                {
                    return NotFound($"未找到ID为 {bimMainTableId} 的仪表板配置");
                }
                return Ok(config);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取仪表板配置失败，BIMainTableId: {BimMainTableId}", bimMainTableId);
                return StatusCode(500, "获取仪表板配置时发生错误");
            }
        }

        [HttpPost("render/charts")]
        public async Task<IActionResult> RenderCharts([FromBody] ChartRequest request)
        {
            try
            {
                // 验证请求
                if (request == null || request.sqlList == null || request.sqlList.Count == 0)
                {
                    return BadRequest(new
                    {
                        success = false,
                        error = "无效的请求: SQL列表不能为空"
                    });
                }

                // 调用服务层处理SQL
                var result = await _chartService.RenderChartAsync(request.sqlList);

                // 解析服务层返回的JSON
                var jsonResult = JsonSerializer.Deserialize<dynamic>(result);

                // 返回统一响应格式
                return new JsonResult(new
                {
                    success = true,
                    data = jsonResult,
                    code = 200
                });
            }
            catch (Exception ex)
            {
                // 记录异常
                _logger.LogError(ex, "渲染图表时发生错误");

                return StatusCode(500, new
                {
                    success = false,
                    error = new
                    {
                        message = ex.Message,
                        type = ex.GetType().Name
                    },
                    code = 500
                });
            }
        }

        // 请求DTO
        public class ChartRequest
        {
            [Required]
            public List<string> sqlList { get; set; }
        }
    }
}
